package com.easy.app.controller;

import cloud.tianai.captcha.application.ImageCaptchaApplication;
import cloud.tianai.captcha.application.vo.CaptchaResponse;
import cloud.tianai.captcha.application.vo.ImageCaptchaVO;
import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.spring.plugins.secondary.SecondaryVerificationApplication;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.easy.framework.common.model.R;
import com.easy.framework.common.utils.AssertUtil;
import com.easy.framework.common.utils.Func;
import com.easy.module.system.cache.ConfCache;
import com.easy.module.system.entity.SysUser;
import com.easy.module.system.service.IEmailCaptchaService;
import com.easy.module.system.service.ISysConfService;
import com.easy.module.system.service.ISysUserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;


@RequestMapping("/captcha")
@RestController
@RequiredArgsConstructor
public class CaptchaController {

    final ISysUserService sysUserService;

    final IEmailCaptchaService emailCaptchaService;

    final ISysConfService sysConfService;


    /**
     * 发送邮箱验证码
     *
     * @param dataMap
     * @return
     */
    @PostMapping("/email/send")
    public R sendEmail(@Validated @RequestBody Map<String, Object> dataMap) {
        String username = MapUtil.getStr(dataMap, "username");
        String templateCode = MapUtil.getStr(dataMap, "templateCode");
        AssertUtil.isTrue(Func.isNotEmpty(username), "用户名不能为空");
        AssertUtil.isTrue(Func.isNotEmpty(templateCode), "模板代码不能为空");
        SysUser sysUser = sysUserService.getByUsername(username);
        AssertUtil.isNotNull(sysUser, "用户不存在");
        String code = RandomUtil.randomNumbers(6);
        Map<String, Object> variables = MapUtil.newHashMap();
        variables.put("code", code);
        variables.put("nickname", sysUser.getNickname());
        variables.put("username", sysUser.getUsername());
        return R.success(emailCaptchaService.sendCaptcha(sysUser.getEmail(), templateCode, code, variables));
    }
//
//
//    @GetMapping("/slider/generate")
//    public R generateCaptcha() {
//        try {
//            return R.success(captchaService.generateCaptcha());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return R.fail();
//    }


    @Autowired
    private ImageCaptchaApplication imageCaptchaApplication;

    @GetMapping("/generate")
    public R<CaptchaResponse<ImageCaptchaVO>> generateCaptcha() {
        boolean captchaEnabled = ConfCache.captchaEnabled();
        if(captchaEnabled) {
            CaptchaResponse<ImageCaptchaVO> response = imageCaptchaApplication.generateCaptcha(ConfCache.captchaType());
            return R.success(response);
        }
        return R.fail(501,"验证已关闭");
    }

    @PostMapping("/generate")
    public CaptchaResponse<ImageCaptchaVO> generateCaptcha2() {
        boolean captchaEnabled = ConfCache.captchaEnabled();
        if(captchaEnabled) {
            CaptchaResponse<ImageCaptchaVO> response = imageCaptchaApplication.generateCaptcha(ConfCache.captchaType());
            return imageCaptchaApplication.generateCaptcha(ConfCache.captchaType());
        }
        return new CaptchaResponse<ImageCaptchaVO>();
    }


    @PostMapping("/check")
    public ApiResponse<?> checkCaptcha(@RequestBody Data data,
                                       HttpServletRequest request) {
        ApiResponse<?> response = imageCaptchaApplication.matching(data.getId(), data.getData());
        if (response.isSuccess()) {
            return ApiResponse.ofSuccess(Collections.singletonMap("id", data.getId()));
        }
        return response;
    }

    @lombok.Data
    public static class Data {
        private String id;
        private ImageCaptchaTrack data;
    }

    /**
     * 二次验证，一般用于机器内部调用，这里为了方便测试
     *
     * @param id id
     * @return boolean
     */
    @GetMapping("/check2")
    public boolean check2Captcha(@RequestParam("id") String id) {
        // 如果开启了二次验证
        if (imageCaptchaApplication instanceof SecondaryVerificationApplication) {
            return ((SecondaryVerificationApplication) imageCaptchaApplication).secondaryVerification(id);
        }
        return false;
    }
}
